package LinkedList;

public class _25_ReverseNodesin_k_Group {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode start = new ListNode(0);
        ListNode p = head,bp = start,bb = head;//bp is every sub circle's start,bb is every sub circle's end
        int count = 0;
        while (p!= null) {
            count++;
            if (count == k) {
                ListNode temp = p.next;
                p.next = null;
                ListNode[] nodes = reverse(bb,p);
                bp.next = nodes[0];
                bp = nodes[1];
                count = 0;
                p  = temp;
                bb = temp;
            }else{
                p = p.next;
            }
        }
        if (count != 0) {
            bp.next = bb;
        }
        return start.next;
    }

    public ListNode[] reverse(ListNode begin,ListNode end){
        ListNode rend = begin,rbegin = end,p = begin;
        ListNode prev = null;
        while(p!=null){
            ListNode temp = p.next;
            p.next = prev;
            prev = p;
            p  = temp;
        }
        return new ListNode[]{rbegin,rend};
    }

    // could not be use,because p is the end of the sub circle, not the start
    //the method asks to begin with the start
    /*public ListNode[] reverse(ListNode begin) {
        ListNode prev = null,p = begin;
        ListNode end = begin;
        ListNode start = null;
        while (p!= null) {
            ListNode temp = p.next;
            p.next = prev;
            prev = p;
            if (temp == null) {
                start = p;
            }
            p = temp;
        }
        ListNode[] nodes = {start,end};
        return nodes;
    }*/

}
